import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  SearchFilter, 
  RecordList, 
  DetailDialog, 
  FilterOptions,
  ExecutionRecord
} from '../components/ExecutionHistory';
import { useTaskHistoryContext } from '../contexts/TaskHistoryContext';
import { useToast } from '../components/Toast';
import ConfirmDialog from '../components/PopupBox/ConfirmDialog';
import { taskService } from '../services/ExecutionService';

const ExecutionHistory: React.FC = () => {
  const navigate = useNavigate();
  const { 
    executionRecords, 
    loading, 
    error, 
    deleteExecutionRecord 
  } = useTaskHistoryContext();
  
  const toast = useToast();

  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterOptions, setFilterOptions] = useState<FilterOptions>({
    status: 'all',
    dateRange: 'all',
    sortOrder: 'newest'
  });
  const [viewMode, setViewMode] = useState<'table' | 'cards'>('table');
  const [currentPage, setCurrentPage] = useState(1);
  const [recordsPerPage] = useState(10);
  const [detailRecord, setDetailRecord] = useState<ExecutionRecord | null>(null);
  const [isDetailOpen, setIsDetailOpen] = useState(false);
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    title: string;
    content: string;
    onConfirm: () => void;
  }>({
    open: false,
    title: '',
    content: '',
    onConfirm: () => {},
  });

  const filteredRecords = useMemo(() => {
    return executionRecords
      .filter(record => {
        if (searchQuery && !record.taskTitle.toLowerCase().includes(searchQuery.toLowerCase()) &&
            !record.taskGuide.toLowerCase().includes(searchQuery.toLowerCase())) {
          return false;
        }

        if (filterOptions.status !== 'all' && record.status !== filterOptions.status) {
          return false;
        }

        if (filterOptions.dateRange !== 'all') {
          const recordDate = record.createdAt;
          const today = new Date();
          today.setHours(0, 0, 0, 0);

          switch (filterOptions.dateRange) {
            case 'today': {
              const tomorrow = new Date(today);
              tomorrow.setDate(tomorrow.getDate() + 1);
              return recordDate >= today && recordDate < tomorrow;
            }
            case 'this-week': {
              const firstDayOfWeek = new Date(today);
              const day = today.getDay() || 7;
              firstDayOfWeek.setDate(today.getDate() - day + 1);
              firstDayOfWeek.setHours(0, 0, 0, 0);
              
              const lastDayOfWeek = new Date(firstDayOfWeek);
              lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 7);
              
              return recordDate >= firstDayOfWeek && recordDate < lastDayOfWeek;
            }
            case 'this-month': {
              const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
              const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0, 23, 59, 59, 999);
              return recordDate >= firstDayOfMonth && recordDate <= lastDayOfMonth;
            }
            default:
              return true;
          }
        }

        return true;
      })
      .sort((a, b) => {
        return filterOptions.sortOrder === 'newest' 
          ? b.createdAt.getTime() - a.createdAt.getTime() 
          : a.createdAt.getTime() - b.createdAt.getTime();
      });
  }, [executionRecords, searchQuery, filterOptions]);

  const paginatedRecords = useMemo(() => {
    const indexOfLastRecord = currentPage * recordsPerPage;
    const indexOfFirstRecord = indexOfLastRecord - recordsPerPage;
    return filteredRecords.slice(indexOfFirstRecord, indexOfLastRecord);
  }, [filteredRecords, currentPage, recordsPerPage]);

  const totalPages = Math.ceil(filteredRecords.length / recordsPerPage);

  const handlePageChange = (pageNumber: number) => {
    setCurrentPage(pageNumber);
  };

  const handleViewDetails = (record: ExecutionRecord) => {
    setDetailRecord(record);
    setIsDetailOpen(true);
  };

  const handleDelete = async (id: string) => {
    const record = executionRecords.find(r => r.id === id);
    setConfirmDialog({
      open: true,
      title: '确认删除',
      content: `确定要删除任务 "${record?.taskTitle}" 的执行记录吗？`,
      onConfirm: async () => {
        try {
          await deleteExecutionRecord(id);
          toast.success('删除成功', '记录已成功删除');
          if (selectedIds.includes(id)) {
            setSelectedIds(prev => prev.filter(selectedId => selectedId !== id));
          }
        } catch (err) {
          toast.error('删除失败', err instanceof Error ? err.message : '删除记录时发生错误');
        }
        setConfirmDialog(prev => ({ ...prev, open: false }));
      },
    });
  };

  const handleDeleteSelected = async () => {
    if (selectedIds.length === 0) return;
    
    setConfirmDialog({
      open: true,
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedIds.length} 条记录吗？`,
      onConfirm: async () => {
        try {
          await Promise.all(selectedIds.map(id => deleteExecutionRecord(id)));
          toast.success('批量删除成功', `成功删除 ${selectedIds.length} 条记录`);
          setSelectedIds([]);
        } catch (err) {
          toast.error('批量删除失败', err instanceof Error ? err.message : '删除记录时发生错误');
        }
        setConfirmDialog(prev => ({ ...prev, open: false }));
      },
    });
  };

  const handleRerun = async (id: string) => {
    const record = executionRecords.find(r => r.id === id);
    if (!record) {
      toast.error('错误', `找不到ID为 ${id} 的记录`);
      return;
    }
    
    setConfirmDialog({
      open: true,
      title: '确认重新运行',
      content: `确定要重新运行任务 "${record.taskTitle}" 吗？`,
      onConfirm: () => {
        setConfirmDialog(prev => ({ ...prev, open: false }));
        
        navigate('/execution', {
          state: {
            selectedTaskIds: [record.id],
            customTasks: [record],
            fromPage: '执行历史'
          }
        });
      },
    });
  };

  useEffect(() => {
    setCurrentPage(1);
  }, [searchQuery, filterOptions]);

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-8 text-gray-900 dark:text-white">执行历史</h1>

      {loading && (
        <div className="text-center py-4 text-gray-500 dark:text-gray-400">
          加载中...
        </div>
      )}

      {error && error !== '请求已取消' && (
        <div className="text-center py-4 text-red-500 dark:text-red-400">
          加载出错: {error}
        </div>
      )}

      <SearchFilter
        filterOptions={filterOptions}
        setFilterOptions={setFilterOptions}
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
        viewMode={viewMode}
        setViewMode={setViewMode}
        selectedIds={selectedIds}
        onDeleteSelected={handleDeleteSelected}
      />

      <RecordList
        records={paginatedRecords}
        viewMode={viewMode}
        selectedIds={selectedIds}
        setSelectedIds={setSelectedIds}
        onViewDetails={handleViewDetails}
        onDelete={handleDelete}
        onRerun={handleRerun}
      />

      {!loading && !error && filteredRecords.length === 0 && (
        <div className="text-center py-8 text-gray-500 dark:text-gray-400">
          没有找到匹配的执行记录
        </div>
      )}

      {filteredRecords.length > recordsPerPage && (
        <div className="flex justify-center mt-4">
          <nav className="inline-flex rounded-md shadow">
            <button
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              className={`px-3 py-1 rounded-l-md border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-sm font-medium ${
                currentPage === 1 
                  ? 'text-gray-300 dark:text-gray-600 cursor-not-allowed' 
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
              }`}
            >
              上一页
            </button>
            
            {[...Array(totalPages)].map((_, i) => (
              <button
                key={i}
                onClick={() => handlePageChange(i + 1)}
                className={`px-3 py-1 border border-gray-300 dark:border-gray-700 text-sm font-medium ${
                  currentPage === i + 1
                    ? 'bg-blue-50 dark:bg-blue-900 text-blue-600 dark:text-blue-300 border-blue-500 z-10'
                    : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                }`}
              >
                {i + 1}
              </button>
            ))}
            
            <button
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              className={`px-3 py-1 rounded-r-md border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-sm font-medium ${
                currentPage === totalPages 
                  ? 'text-gray-300 dark:text-gray-600 cursor-not-allowed' 
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
              }`}
            >
              下一页
            </button>
          </nav>
        </div>
      )}

      <DetailDialog
        record={detailRecord}
        open={isDetailOpen}
        onClose={() => setIsDetailOpen(false)}
        onRerun={handleRerun}
        onDownload={taskService.downloadTaskFile}
      />

      <ConfirmDialog
        open={confirmDialog.open}
        title={confirmDialog.title}
        content={confirmDialog.content}
        onConfirm={confirmDialog.onConfirm}
        onCancel={() => setConfirmDialog(prev => ({ ...prev, open: false }))}
      />
    </div>
  );
};

export default ExecutionHistory; 